using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;

public class netManager : MonoBehaviour {

	private int playerCount;
	private NetworkConnectionError netConnectError;
	
	public string serverAddress="127.0.0.1";
	public int serverPort=25000;
	public bool LANOnly=true;
	
	private gameManager GM;
	
	void Start()
	{
		GM = GameObject.Find("World").GetComponent<gameManager>();
		if(!GM)
			Debug.LogError("gameManager not found.  Add a gameManager to World.");
		serverAddress = GetLocalIPAddress();
	}
	
	public string GetLocalIPAddress()
	{
	   IPHostEntry host;
	   string localIP = "";
	   host = Dns.GetHostEntry(Dns.GetHostName());
	   foreach (IPAddress ip in host.AddressList)
	   {
	     if (ip.AddressFamily == AddressFamily.InterNetwork)
	     {
	       localIP = ip.ToString();
	     }
	   }
	   return localIP;
	}
	
	public void LaunchServer () 
	{
	    bool useNat=false;
		if (LANOnly==true)
			useNat=false;
		else
			useNat=!Network.HavePublicAddress();
		
	    Network.InitializeServer(1, serverPort, useNat);
	}
	
	void OnServerInitialized() {
        Debug.Log("Server initialized and ready");
    }
	
	public void ConnectToServer() 
	{
    	netConnectError = Network.Connect(serverAddress, serverPort);
		GM.ClearState();
		GM.PushState((int)State.waitingforserver);
	}

	void OnPlayerConnected(NetworkPlayer player) {
        Debug.Log("Player " + playerCount++ + " connected from " + player.ipAddress + ":" + player.port);
		networkView.RPC("SetLocalPlayer",player,1-(GM.GetLocalPlayer()));
		GM.ClearState();
		GM.PushState((int)State.playblack);
    }
	
    void OnConnectedToServer() {
        Debug.Log("Connected to server");
		GM.ClearState();
		GM.PushState((int)State.playblack);

    }

    void OnPlayerDisconnected(NetworkPlayer player) {
        Debug.Log("Clean up after player " + player);
        Network.RemoveRPCs(player);
        GM.ClientReset();
		GM.ClientPushState((int)State.mainmenu);
    }

    void OnDisconnectedFromServer(NetworkDisconnection info) {
        if (Network.isServer)
            Debug.Log("Local server connection disconnected");
        else
            if (info == NetworkDisconnection.LostConnection)
                Debug.Log("Lost connection to the server");
            else
                Debug.Log("Successfully diconnected from the server");
		
		GM.ClientReset();
		GM.ClientPushState((int)State.mainmenu);

    }
	
    void OnFailedToConnect(NetworkConnectionError error) {
        Debug.Log("Could not connect to server: " + error);
		netConnectError = error;
		GM.ClearState();
		GM.PushState((int)State.connectfailed);

    }
	
	public void SendClick(RPCMode mode, int index)
	{
		networkView.RPC("ClickLegal", mode, index);
	}
	
	public void ResetClient()
	{
		
		networkView.RPC("ClientReset",RPCMode.Others);
	}
	
	public void PushStateClient(int i)
	{
		networkView.RPC("ClientPushState", RPCMode.Others, i);
	}
	
	public void UpdateServerIPPort(string ip, int prt)
	{
		serverAddress=ip;
		serverPort=prt;
	}
	
}
